import Message from "../model/message";
import {sqlClient as knex} from "../utils/knex";

export async function ins(record: Message) {
    return await knex<Message>('message').insert({
        "receiver": record.receiver,
        "sender": record.sender,
        "title": record.title,
        "content": record.content,
        "createdAt": record.createdAt,
        "data": record.data,
        "type": record.type,
        "isPosted": record.isPosted,
        "isRead": record.isRead
    },['id']);
}

export async function sel_by_receiver(receiver: string): Promise<Message[]> {
    return await knex<Message>('message').select('*').where('receiver', receiver);
}

export async function sel_by_isPosted(isPosted: number): Promise<Message[]> {
    return await knex<Message>('message').select('*').where('isPosted', isPosted);
}

export async function sel_by_receiver_and_isPosted({receiver, isPosted}): Promise<Message[]> {
    return await knex<Message>('message').select('*').where({receiver, isPosted});
}

export async function sel_by_isRead(isRead: number): Promise<Message[]> {
    return await knex<Message>('message').select('*').where('isRead', isRead);
}

export async function sel_by_receiver_and_isRead({receiver, isRead}): Promise<Message[]> {
    return await knex<Message>('message').select('*').where({receiver, isRead});
}

export async function sel_by_type(type: string): Promise<Message[]> {
    return await knex<Message>('message').select('*').where('type', type);
}

export async function sel_by_receiver_and_type({receiver, type}): Promise<Message[]> {
    return await knex<Message>('message').select('*').where({receiver, type});
}

export async function upd_by_id(id: number, updates: any): Promise<number> {
    return await knex<Message>('message').update(updates).where('id', id);
}